import { getRemindRecordAll } from '../../api/user';
import { formatTime } from '../../utils/util.js';
// pages/record/index.js
const compareHHMM = (a, b) => {
  const [ah, am] = a.split(':').map((n) => parseInt(n, 10))
  const [bh, bm] = b.split(':').map((n) => parseInt(n, 10))
  if (ah !== bh) return ah - bh
  return am - bm
}

// function computeStatus(scheduled, actual) {
function computeStatus(status) {
  if ([0, 1].includes(status)) {
    return { text: '未打卡', cls: 'tag--red' }
  } else if ([2, 3].includes(status)) {
    return { text: '已打卡', cls: 'tag--green' }
  } else if (status === 4) {
    return { text: '超时打卡', cls: 'tag--orange' }
  }
}

const app = getApp();

Page({
  data: {
    isAuthorized: false,
    selectedDate: '',
    allRecords: [],
    groupedRecords: [],
    showAdrModal: false,
    adrInput: ''
  },

  onLoad() {
    this.checkAuthStatus();
    // const raw = [
    //   { id: 1, date: '2025-01-01', name: '阿司匹林肠溶片', dose: '100mg/片 × 1片', scheduled: '08:00', actual: '08:00', reminders: 1 },
    //   { id: 2, date: '2025-01-01', name: '二甲双胍缓释片', dose: '500mg/片 × 2片', scheduled: '12:30', actual: '12:45', reminders: 2 },
    //   { id: 3, date: '2025-01-01', name: '辛伐他汀片', dose: '20mg/片 × 1片', scheduled: '18:30', actual: '', reminders: 3 },
    //   { id: 4, date: '2025-01-02', name: '缬沙坦胶囊', dose: '80mg/粒 × 1粒', scheduled: '08:00', actual: '07:58', reminders: 1 },
    //   { id: 5, date: '2025-01-02', name: '叶酸片', dose: '5mg/片 × 1片', scheduled: '21:00', actual: '', reminders: 2 }
    // ]
    // this.setData({ allRecords: raw })
    // this.groupRecords()
  },

  onShow() {
    this.checkAuthStatus();
    this.getRemindRecordAll()
  },

  // 检查授权状态
  checkAuthStatus: function () {
    const isAuthorized = app.globalData.isAuthorized;
    this.setData({
      isAuthorized
    });
  },

  // 处理用户登录
  handleUserLogin: function () {
    wx.showLoading({
      title: '登录中...'
    });

    app.userLogin().then((userInfo) => {
      wx.hideLoading();
      this.setData({
        isAuthorized: true
      });
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
      console.error('登录失败:', err);
    });
  },

  onDateChange(e) {
    this.setData({ selectedDate: e.detail.value }, () => {
      this.getRemindRecordAll()
    })
    // this.groupRecords()
    
  },

  resetDate() {
    this.setData({ selectedDate: '' }, () => {
      this.getRemindRecordAll()
    })
    // this.groupRecords()
  },

  groupRecords() {
    const selected = this.data.selectedDate
    // const filtered = selected ? this.data.allRecords.filter(r => r.date === selected) : this.data.allRecords.slice()
    const filtered = this.data.allRecords.slice()
    // group by date
    const map = {}
    filtered.forEach((r) => {
      // const s = computeStatus(r.scheduled, r.actual)
      const s = computeStatus(r.status)
      const withStatus = { ...r, statusText: s.text, statusClass: s.cls }
      if (!map[r.date]) map[r.date] = []
      map[r.date].push(withStatus)
    })
    const groups = Object.keys(map)
      .sort((a, b) => (a > b ? -1 : 1))
      .map((d) => ({ date: d, items: map[d] }))
    this.setData({ groupedRecords: groups })
  },

  openAdrModal() {
    this.setData({ showAdrModal: true, adrInput: '' })
  },

  closeAdrModal() {
    this.setData({ showAdrModal: false, adrInput: '' })
  },

  onAdrInput(e) {
    this.setData({ adrInput: e.detail.value })
  },

  submitAdr() {
    const val = (this.data.adrInput || '').trim()
    if (!val) {
      wx.showToast({ title: '请填写不良反应描述', icon: 'none' })
      return
    }
    wx.showToast({ title: '已提交', icon: 'success' })
    this.setData({ showAdrModal: false, adrInput: '' })
  },
  
  async getRemindRecordAll() {
    const params = {
      pageNo: 1,
      pageSize: 100,
    }
    if (this.data.selectedDate) {
      params.startDate = this.data.selectedDate
      params.endDate = this.data.selectedDate
    }
    const res = await getRemindRecordAll(params)
    this.setData({ 
      allRecords: res.records.map(r => ({ 
        ...r,
        date: formatTime(new Date(r.reminderDate), 'yyyy-MM-dd')
      }))
    }, () => {
      this.groupRecords()
    })
  }
})

